package com.lemon.smartsafety.ui.activity.common;

import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.common.AreaVo;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.HeaderCallBack;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.ui.adapter.common.AreaAdapter;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.view.list.MultiStateView;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * Created by Cooliean on 16/4/6.
 */
public abstract class AreaBaseActivity extends SwipeBackActivity implements RecyclerTClickListener<AreaVo>, HeaderCallBack {
    @Bind(R.id.tv_tip)
    TextView                  tvTip;
    @Bind(R.id.pullToRefreshRecyclerView)
    PullToRefreshRecyclerView mPullToRefreshRecyclerView;
    @Bind(R.id.multiStateView)
    MultiStateView            mMultiStateView;
    @Bind(R.id.float_button)
    FloatingActionButton      floatButton;
    private LoggerHelper loggerHelper = new LoggerHelper(AreaBaseActivity.class);


    protected String  mParentId     = "";
    protected String  mParentTitle  = "";
    protected boolean isForRegister = false;


    public List<AreaVo> mDataList = new ArrayList<>();

    protected AreaAdapter mAdapter;

    protected View headerView = null;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_list_refresh;
    }


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            isForRegister = getIntent().getBooleanExtra(BundleKey.IS_FOR_REGISTER, false);
            mParentId = getIntent().getStringExtra(BundleKey.AREA_PARENT_ID);
            mParentTitle = getIntent().getStringExtra(BundleKey.AREA_PARENT_TITLE);
        }
        mParentId = StringUtils.nullValue(mParentId);
        mParentTitle = StringUtils.nullValue(mParentTitle);
    }

    @Override
    protected void initViews() {
        super.initViews();
        mAdapter = new AreaAdapter(mDataList, this, "");
        LinearLayoutManager layoutManager = new LinearLayoutManager(IApplication.context(), LinearLayoutManager.VERTICAL, false);
        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
        mPullToRefreshRecyclerView.setLayoutManager(layoutManager);

        mPullToRefreshRecyclerView.setAdapter(mAdapter);
        mPullToRefreshRecyclerView.setOnPullUpToRefreshListener(new PullToRefreshRecyclerView.OnPullUpToRefreshListener() {
            @Override
            public void onRefresh() {
                getNetData();
            }
        });
        initMultiStateView();


        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
        mPullToRefreshRecyclerView.beginRefreshing();


        headerView = getAreaHeaderView(mParentTitle);

        if (mParentTitle.length() != 0) {
            for (int i = 0; i < mPullToRefreshRecyclerView.getHeaderViewCount(); i++) {
                mPullToRefreshRecyclerView.removeHeaderView(i);
            }
            mPullToRefreshRecyclerView.addHeaderView(headerView);
        }

    }

    private void initMultiStateView() {
        View view = mMultiStateView.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.tv_retry);
        view.setVisibility(View.VISIBLE);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getNetData();
            }
        });
    }


    public abstract String getTag();

    public abstract void getNetData();


    @Subscribe
    public void onEventMainThread(HttpCallbackEvent<List<AreaVo>> event) {
        if (getTag().equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mPullToRefreshRecyclerView.onRefreshComplete();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.hidden();
                    httpRefresh(event.getObj());
                } else {
                    httpRefreshError(event.getMsg());
                }
            }
        }
    }


    public void httpRefresh(List<AreaVo> data) {
        if (data != null && !data.isEmpty()) {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
            mDataList.clear();
            mDataList.addAll(data);
            mAdapter.notifyDataSetChanged();
        } else {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
        }
    }


    public void httpRefreshError(String msg) {
        mHUDUtil.showErrorTip(msg);
        mMultiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);

    }


    /**
     * 获得一个顶部控件
     */
    public View getAreaHeaderView(String message) {
        View     header     = LayoutInflater.from(this).inflate(R.layout.view_area_header, (ViewGroup) findViewById(android.R.id.content), false);
        TextView headerView = (TextView) header.findViewById(R.id.tv_title);
        headerView.setText(message);
        header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onHeadClick(v);
            }
        });
        return header;
    }


    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callFinish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(getTag());
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if(!isForRegister && !(this instanceof AreaProvinceActivity) && !(this instanceof AreaCityActivity)){
            getMenuInflater().inflate(R.menu.menu_choose, menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_sure) {
            doSelect();
        }
        return super.onOptionsItemSelected(item);
    }

    public void doSelect(){};

    @Override
    public void onHeadClick(View view) {

    }
}
